package com.example.rg1musicplayerapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.SeekBar;

import java.util.Timer;
import java.util.TimerTask;

public class DetailActivity extends AppCompatActivity {

    private SeekBar seekBar;
    private PlayMusicService.PlayMusicBinder playMusicBinder2;
    private MusicServiceConnection2 musicServiceConnection2;
    private Timer timer;
    private TimerTask timerTask;
    private boolean isChanging=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        seekBar=findViewById(R.id.seekBar);
        Intent musicIntent=new Intent(DetailActivity.this,PlayMusicService.class);
        musicServiceConnection2=new MusicServiceConnection2();
        bindService(musicIntent,musicServiceConnection2,BIND_AUTO_CREATE);

        timer=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
               if(isChanging==true) return;
               if(playMusicBinder2==null) return;
               seekBar.setProgress(playMusicBinder2.getProgress());
            }
        };
        timer.schedule(timerTask,0,10);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(isChanging) playMusicBinder2.seekProgress(i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChanging=true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isChanging=false;
            }
        });
    }

    class MusicServiceConnection2 implements ServiceConnection
    {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            playMusicBinder2=(PlayMusicService.PlayMusicBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

}
